// reqGetCode
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api'
import { setToken, getToken,removeToken } from '@/utils/token'
//home模块的小仓库
//state仓库存储数据的地方
const user = {
    state: {
        //state中的数据默认初始值不要瞎写
        code: '',
        token: getToken(),
        userInfo: {}
    },
    //mutations修改state唯一手段
    mutations: {
        GETCODE(state, code) {
            state.code = code
        },
        USERLOGIN(state, token) {
            state.token = token
        },
        GETUSERINFO(state, userInfo) {
            state.userInfo = userInfo
        },
        CLEAR(state){
            //把仓库中用户信息清空
            state.token = ""
            state.userInfo = {}
            //将本地存储的token空
            removeToken()
        }
    },
    //action处理action 可以书写自己的业务逻辑,也可以处理异步
    actions: {
        //验证码
        async getCode({ commit }, phone) {
            //获取验证码的这个接口,他是把验证码返回了
            let result = await reqGetCode(phone)
            if (result.code == 200) {
                commit('GETCODE', result.data)
                return 'ok'
            } else {
                return Promise.reject(new Error('falie'))
            }
        },
        //用户注册
        async userRegister({ commit }, user) {
            let result = await reqUserRegister(user)
            if (result.code == 200) {
                return 'ok'
            } else {
                return Promise.reject(new Error('faile'))
            }
        },
        //用户登录
        async userLogin({ commit }, user) {
            let result = await reqUserLogin(user)
            //服务器下发token,将来通过带token找服务器要用户信息进行展示
            if (result.code == 200) {
                commit('USERLOGIN', result.data.token)
                //持久化存储
                setToken(result.data.token)
                return 'ok'
            } else {
                return Promise.reject(new Error('faile to login'))
            }
        },
        //获取登录用户信息
        async getUserInfo({ commit }) {
            let result = await reqUserInfo()
            if (result.code == 200) {
                commit('GETUSERINFO', result.data)
                return 'ok'
            }else{
                return Promise.reject(new Error('faile to get UserInfo'))
            }
        },
        //退出登录
        async userLogout({commit}) {
            //通知服务器清除token
            let result = await reqLogout()
            if (result.code == 200) {
                // action中不能操作state
                commit('CLEAR')
                return 'ok'
            }else{
                return Promise.reject(new Error('faile'))
            }
        }
    },
    //getters 可以理解为计算属性,用于简化仓库数据,让组件获取仓库的数据更加方便
    getters: {}
}

export default user